package com.itboy.mall.pms.category.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.itboy.common.exception.CustomException;
import com.itboy.mall.pms.category.service.IMallCategoryService;
import com.itboy.mall.pms.categorybrand.domain.MallCategoryBrand;
import com.itboy.mall.pms.categorybrand.service.IMallCategoryBrandService;
import com.itboy.mall.pms.product.vo.CategoryListLevel3;
import com.itboy.mall.pms.product.vo.Category2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.itboy.common.core.mybatisplus.core.ServicePlusImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itboy.mall.pms.category.bo.MallCategoryAddBo;
import com.itboy.mall.pms.category.bo.MallCategoryQueryBo;
import com.itboy.mall.pms.category.bo.MallCategoryEditBo;
import com.itboy.mall.pms.category.domain.MallCategory;
import com.itboy.mall.pms.category.mapper.MallCategoryMapper;
import com.itboy.mall.pms.category.vo.MallCategoryVo;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品分类Service业务层处理
 *
 * @author itboy
 * @date 2021-07-13
 */
@Service
public class MallCategoryServiceImpl extends ServicePlusImpl<MallCategoryMapper, MallCategory> implements IMallCategoryService {

	@Autowired
	private IMallCategoryBrandService iMallCategoryBrandService;

	@Autowired
	private IMallCategoryService iMallCategoryService;
    @Override
    public MallCategoryVo queryById(String id){
        return getVoById(id, MallCategoryVo.class);
    }


    @Override
    public List<MallCategoryVo> queryList(MallCategoryQueryBo bo) {

        return listVo(buildQueryWrapper(bo), MallCategoryVo.class);
    }

    private LambdaQueryWrapper<MallCategory> buildQueryWrapper(MallCategoryQueryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<MallCategory> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getName()), MallCategory::getName, bo.getName());
        lqw.eq(bo.getShowStatus() != null, MallCategory::getShowStatus, bo.getShowStatus());
        lqw.eq(StrUtil.isNotBlank(bo.getProductUnit()), MallCategory::getProductUnit, bo.getProductUnit());
        lqw.eq(bo.getProductCount() != null, MallCategory::getProductCount, bo.getProductCount());
		lqw.orderByAsc(MallCategory::getSort);
        return lqw;
    }

    @Override
	@Transactional(rollbackFor = Exception.class)
    public Boolean insertByAddBo(MallCategoryAddBo bo) {
        MallCategory add = BeanUtil.toBean(bo, MallCategory.class);
		boolean save = save(add);
		if(add.getParentId()==0L){
			add.setLevel(1L);
			this.baseMapper.updateById(add);
		}else{
			LambdaQueryWrapper<MallCategory> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(MallCategory::getId,add.getParentId());
			MallCategory mallCategory = this.baseMapper.selectOne(queryWrapper);
			add.setLevel(mallCategory.getLevel()+1L);
			this.baseMapper.updateById(add);
		}

		return save;
    }

    @Override
	@Transactional(rollbackFor = Exception.class)
    public Boolean updateByEditBo(MallCategoryEditBo bo) {
        MallCategory update = BeanUtil.toBean(bo, MallCategory.class);

		if(bo.getParentId()==0L){
			bo.setLevel(1L);
		}else{
			LambdaQueryWrapper<MallCategory> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(MallCategory::getId,bo.getParentId());
			MallCategory mallCategory = this.baseMapper.selectOne(queryWrapper);
			bo.setLevel(mallCategory.getLevel()+1L);
		}
		//修改关联分类中冗字段
		LambdaQueryWrapper<MallCategoryBrand> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(MallCategoryBrand::getCatalogId,update.getId());
		List<MallCategoryBrand> mallCategoryBrands = iMallCategoryBrandService.list(queryWrapper);
		if(CollectionUtils.isNotEmpty(mallCategoryBrands)){
			mallCategoryBrands.forEach(e->{
				e.setCatalogName(update.getName());
			});
			iMallCategoryBrandService.updateBatchById(mallCategoryBrands);
		}
		return updateById(update);
    }


    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
			LambdaQueryWrapper<MallCategory> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.in(CollectionUtils.isNotEmpty(ids), MallCategory::getParentId,ids);
			List<MallCategory> mallCategoryList = this.baseMapper.selectList(queryWrapper);
			if(CollectionUtils.isNotEmpty(mallCategoryList)){
              throw new CustomException("该菜单下有子级！");
			}
		}
        return removeByIds(ids);
    }

	@Override
	public String[] getRecursionById(Long id) {
    	List<String>  categoryList=new ArrayList<>();
		List<String> list = findParentId(id, categoryList);
		Collections.reverse(list);
		return list.toArray(new String[list.size()]);
	}

	/**
	 * 递归查询父级
	 * @param id
	 * @param categoryList
	 * @return
	 */
	private List<String> findParentId(Long id,List<String> categoryList) {
		categoryList.add(id.toString());
		MallCategory byId = this.iMallCategoryService.getById(id);
		if(ObjectUtil.isNotNull(byId)&&byId.getParentId()!=0L){
			findParentId(byId.getParentId(),categoryList);
		}
		return categoryList;
	}

	@Override
	public List<MallCategory> getLevel1MallCategory() {
		return iMallCategoryService.list(new LambdaQueryWrapper<MallCategory>().eq(MallCategory::getLevel,1L));
	}

	@Override
	public Map<String, List<Category2Vo>> getCategoryJson() {
		//1.查询所有分类
		List<MallCategory> list = iMallCategoryService.list();
		//2.查询一级分类
		List<MallCategory> categoryLevel1List = getByParentId(list, 0L);
		Map<String, List<Category2Vo>> collect = categoryLevel1List.stream().collect(Collectors.toMap(k -> k.getId().toString(), level1 -> {
			//3.查询二级分类
			List<MallCategory> categoryLevel2List = getByParentId(list, level1.getId());
			//3. 根据二级分类，查找到对应的三级分类
			List<Category2Vo> catelog2Vos =null;
			if(CollectionUtil.isNotEmpty(categoryLevel2List)){
				catelog2Vos=categoryLevel2List.stream().map(level2 -> {
					//4.查询三级分类
					//封装到Catalog3List
					List<CategoryListLevel3> catalog3Lists = null;
					List<MallCategory> categoryLevel3List = getByParentId(list, Long.valueOf(level2.getId()));
					if(CollectionUtil.isNotEmpty(categoryLevel3List)){
						catalog3Lists = categoryLevel3List.stream().map(level3 -> {
							CategoryListLevel3 catalog3List = new CategoryListLevel3(level2.getId().toString(), level3.getId().toString(), level3.getName());
                           return catalog3List;
						}).collect(Collectors.toList());
					}
					return new Category2Vo(level1.getId().toString(), catalog3Lists, level2.getId().toString(), level2.getName());
				}).collect(Collectors.toList());
			}
			return catelog2Vos;
		}));

		return collect;
	}

	/**
	 * 按parentId查询分类
	 * @param list
	 * @param parentId
	 * @return
	 */
	private List<MallCategory> getByParentId(List<MallCategory> list,Long parentId) {
		List<MallCategory> collect = list.stream().filter(item -> item.getParentId() == parentId).collect(Collectors.toList());
		return  collect;
	}
}
